import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.*;


@WebServlet(name = "UserServlet", urlPatterns = {"/register", "/login", "/logout"})
public class UserServlet extends HttpServlet {

    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/baomu?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456"; // 替换为您的MySQL密码

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL JDBC驱动已成功加载");
        } catch (ClassNotFoundException e) {
            System.err.println("无法加载MySQL JDBC驱动");
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置全局字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String path = request.getServletPath();
        System.out.println("请求路径: " + path);

        if (path != null) {
            switch (path) {
                case "/register":
                    handleRegistration(request, response);
                    break;
                case "/login":
                    handleLogin(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    break;
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/logout".equals(path)) {
            handleLogout(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    // 用户注册功能
    private void handleRegistration(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取表单数据
        String username = getParameter(request, "username");
        String password = getParameter(request, "password");
        String phone = getParameter(request, "phone");
        String realname = getParameter(request, "realname");
        String address = getParameter(request, "address");
        String roleStr = getParameter(request, "role");
        String b_price_str = getParameter(request, "b_price");

        // 验证输入
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty() ||
                phone == null || phone.trim().isEmpty() ||
                realname == null || realname.trim().isEmpty() ||
                address == null || address.trim().isEmpty() ||
                roleStr == null || roleStr.trim().isEmpty()) {

            setErrorMessage(request, "所有字段必须填写");
            response.sendRedirect("register.jsp");
            return;
        }

        int role;
        try {
            role = Integer.parseInt(roleStr);
        } catch (NumberFormatException e) {
            setErrorMessage(request, "无效的用户类型");
            response.sendRedirect("register.jsp");
            return;
        }

        // 如果是保姆角色，验证期望薪资
        double b_price = 0;
        if (role == 1) {
            if (b_price_str == null || b_price_str.trim().isEmpty()) {
                setErrorMessage(request, "保姆必须填写期望薪资");
                response.sendRedirect("register.jsp");
                return;
            }

            try {
                b_price = Double.parseDouble(b_price_str);
                if (b_price < 3000 || b_price > 20000) {
                    setErrorMessage(request, "期望薪资应在3000-20000元之间");
                    response.sendRedirect("register.jsp");
                    return;
                }
            } catch (NumberFormatException e) {
                setErrorMessage(request, "无效的薪资格式");
                response.sendRedirect("register.jsp");
                return;
            }
        }

        // 连接数据库并保存用户
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            conn.setAutoCommit(false);

            try {
                // 1. 插入用户表
                String userSql = "INSERT INTO user (u_name, u_pwd, u_phone, u_realname, u_role, u_address) VALUES (?, ?, ?, ?, ?, ?)";
                int userId = -1;

                try (PreparedStatement userStmt = conn.prepareStatement(userSql, Statement.RETURN_GENERATED_KEYS)) {
                    userStmt.setString(1, username);
                    userStmt.setString(2, password);
                    userStmt.setString(3, phone);
                    userStmt.setString(4, realname);
                    userStmt.setInt(5, role);
                    userStmt.setString(6, address);

                    userStmt.executeUpdate();

                    try (ResultSet generatedKeys = userStmt.getGeneratedKeys()) {
                        if (generatedKeys.next()) {
                            userId = generatedKeys.getInt(1);
                        }
                    }
                }

                // 2. 如果是保姆角色，插入保姆表
                if (role == 1) {
                    String baomuSql = "INSERT INTO baomu (u_id, b_name, b_price) VALUES (?, ?, ?)";
                    try (PreparedStatement baomuStmt = conn.prepareStatement(baomuSql)) {
                        baomuStmt.setInt(1, userId);
                        baomuStmt.setString(2, realname);
                        baomuStmt.setDouble(3, b_price);
                        baomuStmt.executeUpdate();
                    }
                }

                conn.commit();

                // 3. 注册成功重定向到登录页
                String roleName = role == 0 ? "雇主" : "保姆";
                setSuccessMessage(request, roleName + "注册成功，请登录");
                response.sendRedirect("login.jsp");

            } catch (SQLException e) {
                conn.rollback();
                handleRegistrationError(e, request, response);
            }
        } catch (SQLException e) {
            handleRegistrationError(e, request, response);
        }
    }

    // 用户登录功能
    private void handleLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取登录参数
        String username = getParameter(request, "username");
        String password = getParameter(request, "password");

        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {

            setErrorMessage(request, "用户名和密码不能为空");
            response.sendRedirect("login.jsp");
            return;
        }

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "SELECT * FROM user WHERE u_name = ? AND u_pwd = ?";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, username);
                stmt.setString(2, password);

                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        // 登录成功
                        int userId = rs.getInt("u_id");
                        String realname = rs.getString("u_realname");
                        int role = rs.getInt("u_role");

                        HttpSession session = request.getSession();
                        session.setAttribute("userId", userId);
                        session.setAttribute("userName", realname);
                        session.setAttribute("userRole", role);

                        // 根据角色重定向
                        if (role == 0) {
                            response.sendRedirect("employer-dashboard.jsp");
                        } else {
                            response.sendRedirect("nanny-dashboard.jsp");
                        }
                    } else {
                        // 登录失败
                        setErrorMessage(request, "用户名或密码错误");
                        response.sendRedirect("login.jsp");
                    }
                }
            }
        } catch (SQLException e) {
            setErrorMessage(request, "数据库错误，请稍后再试");
            response.sendRedirect("login.jsp");
            e.printStackTrace();
        }
    }

    // 用户注销功能
    private void handleLogout(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        response.sendRedirect("login.jsp");
    }

    // 辅助方法：获取URL参数并确保正确处理
    private String getParameter(HttpServletRequest request, String name) {
        String value = request.getParameter(name);
        return (value != null && !value.trim().isEmpty()) ? value.trim() : null;
    }

    // 设置错误消息到 session
    private void setErrorMessage(HttpServletRequest request, String message) {
        HttpSession session = request.getSession();
        session.setAttribute("errorMessage", message);
    }

    // 设置成功消息到 session
    private void setSuccessMessage(HttpServletRequest request, String message) {
        HttpSession session = request.getSession();
        session.setAttribute("successMessage", message);
    }

    // 注册错误处理
    private void handleRegistrationError(SQLException e, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        System.err.println("数据库错误: " + e.getMessage());
        e.printStackTrace();

        // 根据不同错误类型进行特殊处理
        String errorMsg;

        if (e.getErrorCode() == 1062) {
            errorMsg = "用户名已被使用";
        } else if (e.getMessage().contains("doesn't have a default value")) {
            errorMsg = "缺少必填字段";
        } else {
            errorMsg = "系统错误: " + e.getMessage();
        }

        setErrorMessage(request, errorMsg);
        response.sendRedirect("register.jsp");
    }
}